import json
import threading
import time

from PySide6.QtCore import QObject, Slot
from PySide6.QtWebEngineWidgets import QWebEngineView


class JsPython(QObject):
    def __init__(self, app, webEngineView: QWebEngineView):
        super().__init__(None)
        self.sql_text = None
        self.app = app
        self.ui = app.ui
        self.webEngineView: QWebEngineView = webEngineView
        self.page = self.webEngineView.page()

    @Slot(str, result=str)
    def js_set_sql(self, sql_text: str):
        self.sql_text = sql_text
        self.app.tab_sql_query.run_sql_query(sql_text)

    @Slot(str, result=str)
    def js_get_all_table_and_column(self, text: str):
        database = self.ui.database_select.currentText()
        list_data = self.app.mysqldb.table_columns(
            database=database,
        )
        map_table_dict = {}
        for column in list_data:
            list_column = map_table_dict.get(column['TABLE_NAME'], [])
            list_column.append(column['COLUMN_NAME'])
            map_table_dict[column['TABLE_NAME']] = list_column

        data = json.dumps(map_table_dict)
        return data

    def python_set_sql(self, sql: str):
        print(f'set_sql({sql})')
        self.page.runJavaScript(f'set_sql("{sql}")')

    def python_get_sql(self):
        self.page.runJavaScript(f'get_sql()')

    def python_format_sql(self):
        self.page.runJavaScript(f'custom_format_sql()')

    def set_all_table_and_column(self):
        data = self.js_get_all_table_and_column('')
        self.page.runJavaScript(f'set_all_table_and_column({data})')

    @Slot(str, result=str)
    def get_load_page(self, params: str):
        page = self.webEngineView.objectName()
        return page
